package com.demo.service.impl;


import java.util.Date;
import java.util.List;

import com.demo.config.AppConfig;
import com.demo.entity.constants.Constants;
import com.demo.entity.dto.SessionWebUserDto;
import com.demo.entity.enums.ResponseCodeEnum;
import com.demo.entity.enums.UserRoleTypeEnum;
import com.demo.entity.enums.UserStatusEnum;
import com.demo.entity.po.UserInfo;

import com.demo.entity.query.UserInfoQuery;

import com.demo.entity.vo.PaginationResultVO;

import com.demo.exception.BusinessException;
import com.demo.service.EmailCodeService;
import com.demo.service.UserInfoService;

import com.demo.utils.StringTools;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.demo.entity.query.SimplePage;

import com.demo.mappers.UserInfoMapper;

import com.demo.entity.enums.PageSize;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description:用户表serviceImpl
 * @Date:2025-03-01
 * @author：author
*/
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService{

	@Resource
	private UserInfoMapper<UserInfo,UserInfoQuery> userInfoMapper;

	@Resource
	private EmailCodeService emailCodeService;


	@Resource
	private AppConfig appConfig;

	/**
	 * 根据条件查询列表
	 */
	public List<UserInfo> findListByParam(UserInfoQuery query) { 
		return this.userInfoMapper.selectList(query);
	}

	/**
	 * 根据条件查询数量
	 */
	public Integer findCountByParam(UserInfoQuery query){
		return this.userInfoMapper.selectCount(query);
	}

	/**
	 * 分页查询
	 */
	public PaginationResultVO<UserInfo> findListByPage(UserInfoQuery  query) { 
		int count = this.findCountByParam(query);
		int pageSize = query.getPageSize()==null?PageSize.SIZE15.getSize():query.getPageSize();
		SimplePage page = new SimplePage(query.getPageNo(),count,pageSize);
		query.setSimplePage(page);
		List<UserInfo> list = this.findListByParam(query);
		return new PaginationResultVO(count,page.getPageSize(),page.getPageNo(),page.getPageTotal(),list);
	}

	/**
	 * 新增
	 */
	public Integer add(UserInfo bean) { 
		return this.userInfoMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	public Integer addBatch(List<UserInfo> listBean) { 
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.userInfoMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	public Integer addOrUpdateBatch(List<UserInfo> listBean) { 
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.userInfoMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 根据UserId查询
	 */
	public UserInfo getUserInfoByUserId(Long userId) { 
		return this.userInfoMapper.selectByUserId(userId);
	}

	/**
	 * 根据UserId更新
	 */
	public Integer updateUserInfoByUserId(UserInfo bean, Long userId) { 
		return this.userInfoMapper.updateByUserId(bean,userId);
	}

	/**
	 * 根据UserId删除
	 */
	public Integer deleteUserInfoByUserId(Long userId) { 
		return this.userInfoMapper.deleteByUserId(userId);
	}

	/**
	 * 根据Username查询
	 */
	public UserInfo getUserInfoByUsername(String username) { 
		return this.userInfoMapper.selectByUsername(username);
	}

	/**
	 * 根据Username更新
	 */
	public Integer updateUserInfoByUsername(UserInfo bean, String username) { 
		return this.userInfoMapper.updateByUsername(bean,username);
	}

	/**
	 * 根据Username删除
	 */
	public Integer deleteUserInfoByUsername(String username) { 
		return this.userInfoMapper.deleteByUsername(username);
	}

	/**
	 * 根据Email查询
	 */
	public UserInfo getUserInfoByEmail(String email) { 
		return this.userInfoMapper.selectByEmail(email);
	}

	/**
	 * 根据Email更新
	 */
	public Integer updateUserInfoByEmail(UserInfo bean, String email) { 
		return this.userInfoMapper.updateByEmail(bean,email);
	}

	/**
	 * 根据Email删除
	 */
	public Integer deleteUserInfoByEmail(String email) { 
		return this.userInfoMapper.deleteByEmail(email);
	}

	/**
	 * 根据Phone查询
	 */
	public UserInfo getUserInfoByPhone(String phone) { 
		return this.userInfoMapper.selectByPhone(phone);
	}

	/**
	 * 根据Phone更新
	 */
	public Integer updateUserInfoByPhone(UserInfo bean, String phone) { 
		return this.userInfoMapper.updateByPhone(bean,phone);
	}

	/**
	 * 根据Phone删除
	 */
	public Integer deleteUserInfoByPhone(String phone) { 
		return this.userInfoMapper.deleteByPhone(phone);
	}


	@Override
	public SessionWebUserDto login(String account, String password) {
		UserInfo userInfo = this.userInfoMapper.selectByUsername(account);
		if (userInfo == null) {
			userInfo = this.userInfoMapper.selectByEmail(account);
		}
		if (userInfo == null) {
			userInfo = this.userInfoMapper.selectByPhone(account);
		}

		if (null==userInfo||!userInfo.getPassword().equalsIgnoreCase(password)){
			throw new BusinessException("账号或者密码错误");
		}

		SessionWebUserDto webUserDto = new SessionWebUserDto();
		webUserDto.setUserId(userInfo.getUserId());
		webUserDto.setNickName(userInfo.getUsername());
		webUserDto.setAdmin(false);
		webUserDto.setAvatar(userInfo.getAvatar()==null?"":userInfo.getAvatar());
		UserRoleTypeEnum roleTypeEnum = UserRoleTypeEnum.getByType(userInfo.getRole());
		// 管理
		if (roleTypeEnum == UserRoleTypeEnum.ADMIN) {
			webUserDto.setRoleType(UserRoleTypeEnum.ADMIN.getType());
			webUserDto.setAdmin(true);
		}else {
			// 查询系统设置的管理员
			Integer res = checkIsDefaultAdmin(userInfo.getEmail()) ? UserRoleTypeEnum.ADMIN.getType() : roleTypeEnum.getType();
			webUserDto.setRoleType(res);
			webUserDto.setAdmin(res.equals(UserRoleTypeEnum.ADMIN.getType()));
		}

		return webUserDto;
	}

	/**
	 * 重置密码
	 * @param email 邮箱
	 * @param account 账户
	 * @param password 密码
	 * @param emailCode 邮箱验证码
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void restMyPassword(String email, String account, String password, String emailCode) {
		// 输入用户名
		UserInfo dbUserInfo = this.userInfoMapper.selectByUsername(account);
		if (null==dbUserInfo){
			throw new BusinessException("用户名不存在，请注册");
		}
		if (!dbUserInfo.getEmail().equals(email)){
			throw new BusinessException("该用户绑定邮箱不正确，请检查");
		}
		//校验邮箱验证码
		emailCodeService.checkCode(email, emailCode);
		UserInfo updateInfo = new UserInfo();
		updateInfo.setPassword(StringTools.encodeByMD5(password));
		this.userInfoMapper.updateByUserId(updateInfo,dbUserInfo.getUserId());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void register(String email, String account,  String password, String emailCode) {
		//校验邮箱验证码
		emailCodeService.checkCode(email, emailCode);
		UserInfo userInfo = new UserInfo();
		userInfo.setEmail(email);
		// 注册时校验是否是系统管理
		String[] emails = appConfig.getAdminEmails().split(",");
		UserRoleTypeEnum  roleTypeEnum=ArrayUtils.contains(emails,email)?UserRoleTypeEnum.ADMIN:UserRoleTypeEnum.USER;
		userInfo.setRole(roleTypeEnum.getType());
		userInfo.setUsername(account);
		userInfo.setPassword(password);
		saveUserInfo(userInfo);
	}


	/**
	 * 修改用户状态
	 * @param userId
	 * @param status
	 */
	@Override
	public void updateStatus(Long userId, Integer status) {
		UserInfo dbUserInfo = this.userInfoMapper.selectByUserId(userId);
		UserStatusEnum statusEnum = UserStatusEnum.getByStatus(status);

		if(null==dbUserInfo||null==statusEnum){
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}

//		// 是否是系统默认管理员
//		if (checkIsDefaultAdmin(dbUserInfo.getEmail())){
//			throw new BusinessException("无权操作系统默认管理员");
//		}

		UserInfo updateInfo = new UserInfo();
		updateInfo.setStatus(statusEnum.getStatus());
		this.userInfoMapper.updateByUserId(updateInfo,userId);
	}


	// 检查是否是系统默认管理员
	private Boolean checkIsDefaultAdmin(String email){
		String[] adminEmails = appConfig.getAdminEmails().split(",");
		return  ArrayUtils.contains(adminEmails,email);
	}

	/**
	 * 保存用户信息
	 * @param bean
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveUserInfo(UserInfo bean) {
		// 校验角色类型
		UserRoleTypeEnum typeEnum = UserRoleTypeEnum.getByType(bean.getRole());
		if (typeEnum ==null){
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}

		//用户名不能重复
		UserInfo dbUserInfo4UserName = this.userInfoMapper.selectByUsername(bean.getUsername());
		if (dbUserInfo4UserName!=null&&bean.getUserId()==null){
			throw new BusinessException("用户名已经存在");
		}

		UserInfo dbUserInfo4Phone = this.userInfoMapper.selectByPhone(bean.getPhone());
		// 修改用户信息 根据邮箱查询为空 邮箱查询出来的数据不等于
		if((dbUserInfo4Phone!=null&&bean.getUserId()!=null&&!bean.getUserId().equals(dbUserInfo4Phone.getUserId()))||
				(bean.getUserId()==null&&dbUserInfo4Phone!=null)){
			throw new BusinessException("该号码已经绑定其他账号");
		}

		 Date curDate= new Date();
		//新增
		if (bean.getUserId()==null){
			bean.setStatus(UserStatusEnum.ENABLE.getStatus());
			bean.setCreateTime(curDate);
			bean.setPassword(StringTools.encodeByMD5(bean.getPassword()));
			this.userInfoMapper.insert(bean);
		}else{
			bean.setUpdateTime(curDate);
			bean.setStatus(null);
			bean.setPassword(null);
			this.userInfoMapper.updateByUserId(bean,bean.getUserId());
		}

		if (bean.getEmail()==null){
			return;
		}
		UserInfoQuery query =	new UserInfoQuery();
		query.setEmail(bean.getEmail());
		Integer count = userInfoMapper.selectCount(query);
		if (count>=Constants.TWO){
			throw new BusinessException("该邮箱已经绑定其他账号，请重试");
		}
	}
}